//
//  CMTip.swift
//  CMKit
//
//  Created by travel on 2016/12/15.
//  Copyright © 2016年 covermedia. All rights reserved.
//

import UIKit


public class CMTipView: UIView {
    fileprivate(set) lazy var titleLabel = UILabel()
    fileprivate var presentTimer = Timer()
    fileprivate var presentBlock:((UIView) -> Void)?
    
    fileprivate var hideTimer = Timer()
    fileprivate var hideBlock:((UIView) -> Void)?
    
    
    init(title:String) {
        super.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44))
        titleLabel.numberOfLines = 0
        titleLabel.textAlignment = .center
        addSubview(titleLabel)
    }
    
    func present(_ time:TimeInterval = 0.3, present:((UIView) -> Void)?) {
        presentBlock = present
        presentTimer.invalidate()
        hideTimer.invalidate()
        if time > 0 {
            presentTimer = Timer.scheduledTimer(timeInterval: time, target: self, selector: #selector(CMTipView.handlePresent), userInfo: nil, repeats: false)
        } else {
            handlePresent()
        }
    }
    
    func handlePresent() {
        presentBlock?(self)
    }
    
    func hide(_ time:TimeInterval = 0.3, hide:((UIView) -> Void)?) {
        hideBlock = hide
        hideTimer.invalidate()
        presentTimer.invalidate()
        if time > 0 {
            hideTimer = Timer.scheduledTimer(timeInterval: time, target: self, selector: #selector(CMTipView.hidePresent), userInfo: nil, repeats: false)
        } else {
            hidePresent()
        }
    }
    
    func hidePresent() {
        hideBlock?(self)
    }
    
    func dismiss() {
        presentTimer.invalidate()
        hideTimer.invalidate()
        removeFromSuperview()
    }
    
    override public func layoutSubviews() {
        super.layoutSubviews()
        titleLabel.frame = bounds
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

public class CMTips {
    fileprivate var viewStore = CMViewStore()
    
    public static let shared = CMTips()
    
    public class func tipView(inView view:UIView? = nil) -> UIView? {
        return self.shared.viewStore.view(inView: view)
    }
    
    
    public class func hideTip(inView view:UIView? = nil) {
        _ = self.shared.viewStore.hideView(inView: view)
    }
    
    public class func showTip(_ view:UIView,
                            inView:UIView? = nil,
                            removePreTip:Bool = true,
                            layoutBlock:((UIView, UIView) -> Void)? = nil) {
        self.shared.viewStore.showView(view, inView: inView, removePre: removePreTip, layoutBlock: layoutBlock)
    }
}


public extension CMTips {
    /**
     显示tip（更新了多少条消息）
     
     - parameter title:           标题
     - parameter font:            字体
     - parameter textColor:       颜色
     - parameter backgroundColor: 背景色
     - parameter inView:          待显示view的容器
     */
    public class func showMessage(_ title: String, font:UIFont = UIFont.systemFont(ofSize: UIFont.smallSystemFontSize), textColor: UIColor = UIColor.white, backgroundColor: UIColor = UIColor.lightGray, inView:UIView? = nil) {
        if let pre = self.tipView(inView: inView) as? CMTipView {
            pre.dismiss()
        }
        
        let tipView = CMTipView.init(title: title)
        tipView.titleLabel.textColor = textColor
        tipView.titleLabel.font = font
        tipView.titleLabel.text = title
        tipView.backgroundColor = backgroundColor
        tipView.isHidden = true
        
        self.showTip(tipView, inView: inView, removePreTip: false) { (tip:UIView, container:UIView) in
            let width = container.frame.width > 0 ? container.frame.width : UIScreen.main.bounds.width
            let size = CGSize(width: width, height: 99999)
            let calcSize = (title as NSString).boundingRect(with: size,
                                                            options: NSStringDrawingOptions.usesLineFragmentOrigin,
                                                            attributes: [NSFontAttributeName: font], context: nil)
            let height = ceil(calcSize.height)
            let padding = 18.pixel
            tipView.frame = CGRect(x: 0, y: 0, width: width, height: -(height + 2 * padding))
            tipView.autoresizingMask = .flexibleWidth
            
            tipView.present(0.3, present: { (view:UIView) in
                view.isHidden = false
                view.frame.origin.y = -view.frame.height
                UIView.animate(withDuration: 0.3, animations: {
                    view.frame.origin.y = 0
                }, completion: { (Bool) in
                    tipView.hide(1, hide: { (view:UIView) in
                        UIView.animate(withDuration: 0.3, animations: {
                            view.frame.origin.y = -view.frame.height
                        }, completion: { (Bool) in
                            view.removeFromSuperview()
                        })
                    })
                })
            })
        }
    }
}

